package com.bluetooth;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.fragment.app.ListFragment;

import com.itianshan.wheel.CloudBluetoothCarActivity;
import com.itianshan.wheel.R;
import com.usbserial.util.HexDump;

import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Set;

public class BluetoothDevicesFragment extends ListFragment {
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayList<BluetoothDevicesFragment.ListItem> listItems = new ArrayList<>();
    private ArrayAdapter<BluetoothDevicesFragment.ListItem> listAdapter;
    private boolean is_cloud = false;
    class ListItem {
        BluetoothDevice device;
        String name;
        String address;

        ListItem(BluetoothDevice device) {
            this.device = device;
            this.name = device.getName();
            this.address = device.getAddress();
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            //setEmptyText(getString(R.string.error_bluetooth_not_supported));
            return;
        }
        // 如果本地蓝牙没有开启，则开启
        if (!mBluetoothAdapter.isEnabled())
        {
            // 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择，比如用户单击了Yes开启，
            // 那么将会收到RESULT_OK的结果，
            // 如果RESULT_CANCELED则代表用户不愿意开启蓝牙
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(mIntent, 1);
            // 用enable()方法来开启，无需询问用户(实惠无声息的开启蓝牙设备),这时就需要用到android.permission.BLUETOOTH_ADMIN权限。
            // mBluetoothAdapter.enable();
            // mBluetoothAdapter.disable();//关闭蓝牙
        }
        // 如果正在搜索，就先取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
        mBluetoothAdapter.startDiscovery();
        listAdapter = new ArrayAdapter<BluetoothDevicesFragment.ListItem>(getActivity(), 0, listItems) {
            @Override
            public View getView(int position, View view, ViewGroup parent) {
                BluetoothDevicesFragment.ListItem item = listItems.get(position);
                String car="" ;
                if (view == null)
                    view = getActivity().getLayoutInflater().inflate(R.layout.device_list_item, parent, false);
                TextView text1 = view.findViewById(R.id.text1);
                TextView text2 = view.findViewById(R.id.text2);
                if(item.name.equals("IoTCar")){
                    car = getString(R.string.car);
                }
                text1.setText(car + item.name);
                text2.setText(item.address);
                return view;
            }
        };
        Intent intent = getActivity().getIntent();
        is_cloud = intent.getBooleanExtra("is_cloud",false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(null);
        View header = getActivity().getLayoutInflater().inflate(R.layout.device_list_header, null, false);
        TextView title = header.findViewById(R.id.device_title);
        title.setText(getString(R.string.bluetooth_devices));
        getListView().addHeaderView(header, null, false);
        setEmptyText(getString(R.string.no_bluetooth));
        ((TextView) getListView().getEmptyView()).setTextSize(18);

        setListAdapter(listAdapter);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_devices, menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.refresh) {
            refresh();
            return true;
        } else if (id ==R.id.baud_rate) {
            return true;
        } else if (id ==R.id.read_mode) {
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }
        @Override
    public void onResume() {
        super.onResume();
        refresh();
    }
    void refresh() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();

        listItems.clear();
        if (devices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : devices) {
                listItems.add(new BluetoothDevicesFragment.ListItem(bluetoothDevice));
            }
        }
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        BluetoothDevicesFragment.ListItem item = listItems.get(position-1);
        if(is_cloud) {
            //开启云端控制
            long add = Long.parseLong(item.address.replace(":",""),16);

            //String roomId = String.valueOf(addressToInt(item.address)%100000000);//取硬件地址转换后的后8位为房间号

            String roomId= String.valueOf(add%100000000);
            String userId = roomId ;
            Intent intent = new Intent(getActivity(), CloudBluetoothCarActivity.class);
            intent.putExtra("user_id", userId); //云房间的用户ID
            intent.putExtra("room_id", roomId); //云房间号，一般与用户ID一致
            intent.putExtra("DEVICE_NAME", (String) item.name);
            intent.putExtra("DEVICE_ADDRESS", (String) item.address);
            startActivity(intent);
        } else {
            //进入本地控制
            Intent intent = new Intent(getActivity(), BluetoothWheelActivity.class);
            intent.putExtra("DEVICE_NAME", (String) item.name);
            intent.putExtra("DEVICE_ADDRESS", (String) item.address);
            startActivity(intent);
        }
    }

    //十六进制的硬件地址转成十进制数
    private long addressToInt(String address){
        String hexStr = address.replace(":","");
        hexStr = hexStr.toUpperCase();
        int s = 0;
        long result=0;
        for(int i = 0; i < hexStr.length() ; i++){
            if(0x30<=hexStr.charAt(i)&&hexStr.charAt(i)<=0x39){
                s = hexStr.charAt(i)-0x30;
            }
            if(0x40<hexStr.charAt(i)&&hexStr.charAt(i)<0x47){
                s = hexStr.charAt(i)-0x37;
            }
            result += s*Math.pow(16,hexStr.length()-1-i);
        }

        return result;
    }

}
